var categoriesArray = [];

/**
 * At page launch...
 */
$(document).ready(function() {
	
	$.getJSON("../shopping/shopping.php?query=category", function( data ) {
		var items = [];
		var i = 0;
		$.each( data, function( key, val ) {
			items.push('<li id="categorie_' + val.nom + '"><a onclick="filtrerCategorie(\''+val.nom+'\');return false;" href="#"><img src="'+val.image+'" alt=""></a></li>');
		});
		$('#listCategorie').append(items.join(''));
	});

	$("#rechercheTag").keyup(function(){
		var txt = $(this).val();
		if (txt.toUpperCase() == "CANARD") {
			//window.location = "../webgl/index.html";
			$("#container").html("<div id='webglContainer'><iframe id='webgl' src='webgl/index.html'></iframe></div>");
		} else {
			search(txt);
		}
	});

	search('');
});



/**
 * Search a product
 */
function search(text) {
	$.getJSON("../shopping/shopping.php?query=search&product="+text, function( data ) {
		var items = [];
		$("#listCategorie li").hide();
		$.each( data, function( key, val ) {
			$.each( val.categories, function( k, v ) {
				$("#categorie_" + v.nom).show();
			});	
			items.push("<div class='item'><a href='"+val.lien+"' target='_blank'><img src='" + val.image + "' alt='Owl Image'></a><p>" + val.nom + "<br /><span>" + val.prix + " €</span></p></div>");
		});
		$('#listProduits').remove();		
		$('#listCategorie').after("<div id='listProduits' class='owl-carousel'></div>");
		$('#listProduits').append(items.join('')).owlCarousel({ 
	      	items : 10,
	      	itemsDesktop : [1199,3],
	      	itemsDesktopSmall : [979,3] 
	  	});
	});
}

/**
 * Filters the products
 */
function filtrerCategorie(cat) {
	categoriesArray.push(cat);
	var cats = arrayToString(categoriesArray);
	$('#listProduits').empty();
	$.getJSON("../shopping/shopping.php?query=search&category="+cats+"&product=" + $('#rechercheTag').val(), function( data ) {
		var items = [];
		$("#listCategorie li").hide();
		$.each( data, function( key, val ) {
			$.each( val.categories, function( k, v ) {
				$("#categorie_" + v.nom).show();
			});		
			items.push("<div class='item'><a href='"+val.lien+"' target='_blank'><img src='" + val.image + "' alt='Owl Image'></a><p>" + val.nom + "<br /><span>" + val.prix + " €</span></p></div>");
		});
		$('#listProduits').remove();		
		$('#listCategorie').after("<div id='listProduits' class='owl-carousel'></div>");
		$('#listProduits').append(items.join('')).owlCarousel({ 
	      	items : 10,
	      	itemsDesktop : [1199,3],
	      	itemsDesktopSmall : [979,3] 
	  	});
	});
}


function arrayToString(arr) {
	var ret = arr[0];
	for (var i=1; i<arr.length; i++) {
		ret += "," + arr[i];
	}

	return ret;
}